package com.hengxinguotong.zhihuichengjian.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.NewsListAdapter;
import com.hengxinguotong.zhihuichengjian.ui.app.BaseFragment;
import com.hengxinguotong.zhihuichengjian.bean.News;
import com.hengxinguotong.zhihuichengjian.bean.NewsInfo;
import com.hengxinguotong.zhihuichengjian.ui.MainActivity;
import com.hengxinguotong.zhihuichengjian.ui.WebViewActivity;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshBase;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshListView;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2017/7/11.
 */

public class ChengxiangFragment extends BaseFragment {

    @BindView(R.id.news_lv)
    PullToRefreshListView newsLv;

    private MainActivity mainActivity;
    private View rootView = null;
    private NewsListAdapter adapter;
    private int pageIndex = 1;
    private int type;//资讯类型(2:广告;3:城乡建设;4:海绵城市;5:综合管廊;6:BIM)
    private List<News> newsList;

    public static ChengxiangFragment newInstance(String s){
        Bundle bundle = new Bundle();
        bundle.putString("news",s);
        ChengxiangFragment fragment = new ChengxiangFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_chengxiang, null);
            ButterKnife.bind(this, rootView);
            mainActivity = (MainActivity) getActivity();
            ButterKnife.bind(this, rootView);
//            newsLv.setDividerPadding(10);
            newsLv.setMode(PullToRefreshBase.Mode.BOTH);
            getType();
            setListener();
        }else {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
        }
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    private void getType(){
        Bundle bundle = getArguments();
        String newsType = bundle.getString("news");//资讯类型(2:广告;3:城乡建设;4:海绵城市;5:综合管廊;6:BIM)
        switch (newsType){
            case "cxjs":
                type = 3;
                break;
            case "hmcs":
                type = 4;
                break;
            case "zhgl":
                type = 5;
                break;
            case "bim":
                type = 6;
                break;
        }
    }

    private void setListener(){
        newsLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(mainActivity, WebViewActivity.class);
                intent.putExtra("news", newsList.get(position -1));
                intent.putExtra("title", "新闻资讯");
                mainActivity.startActivity(intent);
            }
        });

        newsLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageIndex = 1;
                getNewsList(null);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getNewsList(null);
            }
        });
    }

    /*
     *获取资讯信息
     */
    private void getNewsList(String alert) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("pageNum", pageIndex + "");
            jsonObject.put("type", type);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
//        params.addBodyParameter("pageNum", pageIndex + "");
        Utils.requestData(alert, mainActivity, "/news/queryInformationList/" + SPUtil.getString(mainActivity,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if(newsLv.isRefreshing()){
                    newsLv.onRefreshComplete();
                }
                if(!Utils.isEmpty(json)){
                    SPUtil.put(mainActivity, "newsList", json);
                    Gson gson = new Gson();
                    NewsInfo newsInfo = gson.fromJson(json, NewsInfo.class);
                    processNews(newsInfo.getValue());
                }else{
                    showEmptyView(newsLv);
                }
            }

            @Override
            public void onFailure(String json) {
                if(newsLv.isRefreshing()){
                    newsLv.onRefreshComplete();
                }
                showEmptyView(newsLv);
            }
        });
    }

    private void processNews(List<News> datas){
        if(pageIndex == 1){
            if(datas.size() == 0){
                showEmptyView(newsLv);
            }else{
                dismissEmptyView();
            }
            newsList = datas;
            adapter = new NewsListAdapter(mainActivity, newsList);
            newsLv.setAdapter(adapter);
            if(datas.size() == Utils.ONCECOUNT){
                newsLv.setMode(PullToRefreshBase.Mode.BOTH);
            }
        }else{
            newsList.addAll(datas);
            adapter.notifyDataSetChanged();
        }

        if(datas.size() < Utils.ONCECOUNT){
            newsLv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        }

        if (datas.size() != 0) {
            pageIndex++;
        }
    }

    @Override
    public void onLazyLoad() {
        getNewsList("加载中…");
    }
}
